-module(bnode_action).
-include("btree.hrl").

%% API
-export([forward/2]).

forward(BTree, #bn{props = Props, id = NodeId} = BNode) ->
    Action = proplists:get_value(action, Props),
    Result =
        case Action of
            [{M, F, A}] ->
                erlang:apply(M, F, [BTree#bt{entry = NodeId}, A]);
            [{M, F}] ->
                erlang:apply(M, F, BTree#bt{entry = NodeId});
            [F] when is_function(F, 1) ->
                F(BTree#bt{entry = NodeId});
            _ ->
                ?FAILURE
        end,
    case case Result of
             {ok, BTree1, Val} ->
                 {Val, BTree1};
             _ ->
                 {Result, BTree}
         end of
        {?RUNNING, NewBTree} -> % 还在执行
            NewBTree#bt{result = BNode};
        {NewRes, NewBTree} ->   % 执行结束
            bnode_api:backward(NewBTree#bt{result = NewRes}, BNode)
    end.

